#!/bin/bash

# 洗护系统健康检查脚本

set -e

# 配置
BACKEND_URL="http://localhost:8080"
MAX_RETRIES=30
RETRY_INTERVAL=2

echo "🔍 开始健康检查..."

# 检查后端服务
check_backend() {
    echo "检查后端服务..."
    for i in $(seq 1 $MAX_RETRIES); do
        if curl -f -s "${BACKEND_URL}/api/test/db-info" > /dev/null 2>&1; then
            echo "✅ 后端服务正常"
            return 0
        fi
        echo "⏳ 等待后端服务启动... ($i/$MAX_RETRIES)"
        sleep $RETRY_INTERVAL
    done
    echo "❌ 后端服务检查失败"
    return 1
}

# 检查数据库连接
check_database() {
    echo "检查数据库连接..."
    response=$(curl -s "${BACKEND_URL}/api/test/db-info")
    if echo "$response" | grep -q '"success":true'; then
        echo "✅ 数据库连接正常"
        return 0
    else
        echo "❌ 数据库连接失败"
        echo "响应: $response"
        return 1
    fi
}

# 检查认证功能
check_auth() {
    echo "检查认证功能..."
    response=$(curl -s -X POST "${BACKEND_URL}/api/auth/login" \
        -H "Content-Type: application/json" \
        -d '{"username":"testuser","password":"123456"}')
    
    if echo "$response" | grep -q '"success":true'; then
        echo "✅ 认证功能正常"
        return 0
    else
        echo "❌ 认证功能失败"
        echo "响应: $response"
        return 1
    fi
}

# 检查API接口
check_apis() {
    echo "检查核心API接口..."
    
    # 检查服务分类接口
    if curl -f -s "${BACKEND_URL}/api/services/categories" > /dev/null 2>&1; then
        echo "✅ 服务分类接口正常"
    else
        echo "❌ 服务分类接口失败"
        return 1
    fi
    
    # 检查商家列表接口
    if curl -f -s "${BACKEND_URL}/api/merchants" > /dev/null 2>&1; then
        echo "✅ 商家列表接口正常"
    else
        echo "❌ 商家列表接口失败"
        return 1
    fi
    
    return 0
}

# 主检查流程
main() {
    echo "🚀 洗护系统健康检查开始"
    echo "目标地址: $BACKEND_URL"
    echo "最大重试次数: $MAX_RETRIES"
    echo "重试间隔: ${RETRY_INTERVAL}秒"
    echo "----------------------------------------"
    
    # 执行检查
    if check_backend && check_database && check_auth && check_apis; then
        echo "----------------------------------------"
        echo "🎉 所有检查通过！系统运行正常"
        echo "📊 系统状态: 健康"
        echo "🌐 访问地址: $BACKEND_URL"
        exit 0
    else
        echo "----------------------------------------"
        echo "❌ 健康检查失败！"
        echo "📊 系统状态: 异常"
        echo "🔧 请检查日志并修复问题"
        exit 1
    fi
}

# 如果直接运行脚本
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi
